<?php
/*
 * 虾卖
 * */
namespace app\cgi\controller;

use think\Db;

set_time_limit(300);
class Upload extends Base{
    public $post = null;
    private $time = null;
    public function _initialize(){
        $this->mustLogin();
        $this->time = time();
        $lastCount = Db::name('file')->where("user_id=".$this->userInfo['id']." AND {$this->time}-mtime<10")->count();
        9 < $lastCount && api_response_err('请求太频繁，请稍后');
    }

    /**
     * 图片上传
     */
    public function image(){
        $file = $this->request->file('file');
        if( !$file ) {
            $this->responseError('请选择正确的文件');
        }
        $original=$file->getInfo('name');
        $file->validate([
            'size'=>4*1024*1024,
            'ext'=>'jpg,png,jpeg,bmp,gif'
        ]);
        $dir = getSaveImgDir();
        $path = ROOT_PATH .'public'.$dir;
        $info = $file->move($path);
        if (!$info) {
            $this->responseError($file->getError());
        }
        $data = $this->request->root() . $dir . $info->getSaveName();
        $insert = [
            'cate'     => 3,
            'name'     => $data,
            'original' => $original,
            'domain'   => '',
            'type'     => $info->getInfo('type'),
            'size'     => $info->getInfo('size'),
            'mtime'    => $this->time,
            'user_id'  => $this->userInfo['id'],
            'ty_id'    => $this->ty_id,
        ];
        Db::name('file')->insert($insert);
        $this->response('',['url'=>$insert['domain'].$data]);
    }
}